package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec
import javax.servlet.RequestDispatcher;
import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.ParseException
import java.text.SimpleDateFormat;
import java.time.Instant

import org.apache.commons.codec.binary.Base64
import org.apache.commons.codec.digest.DigestUtils
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import cn.com.kh.hst.ThreeDesUtil
import cn.com.kh.KHUtil;
import cn.com.kh.getProperty;


/**
 *
 * @Title: aipHSTLabel_Customers
 * @Description:华盛证券 标签客户查询接口
 * @author: xrm
 * @date 2022-11-24 15:52:00
 *
 */

public class aipHSTLabel_Customers implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(aipHSTLabel_Customers.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        String inData = "";
        String outData = "";
        String totalData = "";
        String dataSourceID = "dataSource";


        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData );
        }

        inData = URLDecoder.decode(inData, "UTF-8");
        log.debug("原始inData URLDecoder:" + inData);

        try {

            long startTime = System.currentTimeMillis();
            String reJson = null;
            long endTime = 0;
			log.debug("dayin");
			JSONObject inObject = new JSONObject(inData);
			log.debug("原始inObject inObject:" + inObject);
            //鉴权变量
            String appid = getProperty.get("appid");
            String appsecret = getProperty.get("appsecret");

            //sign加密前后
            String signfront = "";
            String signafter = "";
			
			def lastid = "0";
			def limit = "500";
			def tagname = inObject.getString("tagname");//活动名称
			//def token = "691e0237c2c14caebb245605d3aab143-651"
			

           	List hst_Activitylist = eliteBean.chaxun_sql("select tab_activity_id from hst_Activity where tab_activity_name='"+tagname+"'", "dataSource");//查询批次
			String Temp_Guid = hst_Activitylist.get(0).get("tab_activity_id");//活动id
			log.debug("Temp_Guid:"+Temp_Guid);
			//String Temp_Guid = KHUtil.getRandomString(36).toUpperCase();

			//生成批次号规则
			long time=new Date().getTime();
			System.out.println(""+time);
			Date dates=new Date(time);
			SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddhhmmss");
			String times=sdf.format(dates);

			String batchid2 = "HST" + times; //批次号
			String batch_name = tagname+"-"+times  //批次名称
            String message2 = "";
            boolean nextPage=true;
			
			
			while (nextPage) {
	            String sign_time=Instant.now().getEpochSecond();
	            log.debug("解析信息-" +  "sign_time: " + sign_time);
	
	            HashMap<String, String> paramHashMap = new HashMap<String, String>() {
	                {
						//put("token", token);//上次请求最后数据ID，默认0
						put("lastid", lastid);//上次请求最后数据ID，默认0
						put("limit", limit);//页码，默认1000
						put("tag", tagname);//标签名
						put("count", "");//是否计算数据量，有任意值时时分页参数失效，默认为空
						put("sign_time", sign_time);
	                }
	            };
	
	            log.debug("paramHashMap：" + paramHashMap);
	            //自然排序 升序参数F
	            signfront= ThreeDesUtil.sortMap(paramHashMap,appid,appsecret);
	            log.debug("sign加密MD5前：" + signfront);
	            signafter = Util.getMD5Str(signfront);
	            log.debug("sign加密MD5后：" + signafter);
	
	            //拼接接口入参
	            paramHashMap.put("client_key", appid);
	            paramHashMap.put("sign", signafter);
	
	            String injson=ThreeDesUtil.SplicingMap(paramHashMap,"&");
	            log.debug("injson:" + injson);
	
	            totalData = Querypromocode(eliteBean, injson,dataSourceID,Temp_Guid,tagname,batchid2,batch_name);
				//解析SSO返回信息
				JSONObject jsonObject = new JSONObject(totalData);
				log.debug("jsonObject:"+jsonObject);
				lastid = GetJV(jsonObject, "lastid");//下一页请求带上的值
			    message2 = GetJV(jsonObject, "message");//下一页请求带上的值
				
				//不等于0继续下拉
				if(lastid!="0"){
					nextPage=true;
			    }
				//等于0数据下拉完，等于空代表无数据
				if(lastid=="0"||lastid==""){
					nextPage=false;
			    }
				
				log.debug("lastid0:" + lastid+"nextPage0:" + nextPage);				
			}
            outData = "{\"result\":\"1\",\"message\":\"处理成功("+ message2 +")\",\"data\":[]}";


        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            outData = "{\"result\":\"-1\",\"message\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
        }

        return outData;
    }

    //标签客户查询接口 URI:	/mp-dabs/queryTagMember
    public static String Querypromocode(EliteBean eliteBean , String injson, String dataSourceID ,String Temp_Guid,String tagname,String batchid2,String batch_name) {

        long startTime = System.currentTimeMillis();
        log.debug("处理开始时间:" + startTime);

        long endTime = System.currentTimeMillis();

        String reJson = null;
		String lastid="";
		//boolean nextPage =false;
        try {

            String doURL = getProperty.get("HSTURL");
            doURL = doURL+"/mp-dabs/queryTagMember";
            log.debug("doURL:" + doURL);
            Map<String, String> headMap = new HashMap<String, String>();
            headMap.put("Content-Type", "application/x-www-form-urlencoded");
            def getResult = Util.doHttpPostUseHead(doURL, injson, "UTF-8", 10000, 0, headMap);
            log.debug("getResult:" + getResult);

            //解析SSO返回信息
            JSONObject jsonObject = new JSONObject(getResult);
            String code = GetJV(jsonObject, "code");
            String result = GetJV(jsonObject, "result");
			String num = GetJV(jsonObject, "num");
            JSONObject dataObject;

            log.debug("code:" + code);
			
			def dataresult;
			
			//查询批次是否已经存在了
			List dataczresult = eliteBean.chaxun_sql("Select rec_guid From hst_activity_batch Where batchid = '" + batchid2 + "'", "dataSource");
			if (dataczresult.size() <= 0) {
				log.debug("批次不存在，则新增！");
				dataresult = eliteBean.update("INSERT INTO hst_activity_batch(rec_guid,batchid,batchname,tab_activity_id,file_name,file_rownum,valid_num,invalid_num,import_time,starttime,state,Modifiedby,Modifieddate,wholestate,batchgeneration) VALUE (uuid(), '"+batchid2+"', '"+batch_name+"', '"+Temp_Guid+"', null, null, null, null, now(), now(), '1', 'SELITE', now(), null,'1')", "dataSource");
			}else{
				log.debug("批次存在！");
			}
			
            if(code == "00000") {
				dataObject = new JSONObject(result);
                lastid= GetJV(dataObject, "lastid");
				String dataList = GetJV(dataObject, "data");
                //nextPage = GetJV(dataObject, "nextPage");
				//nextPage = Boolean.valueOf(GetJV(dataObject, "nextPage"));
				log.debug("lastid1："+lastid);
				
				
				if(dataList.size()>0) {

	                JSONArray arrJsonArray = new JSONArray(dataList);

					int arrInt = arrJsonArray.length();
	                for (int i = 0; i < arrInt; i++) {
	                    JSONObject arrSmsJson = arrJsonArray.getJSONObject(i);
	                    
						String idNo =GetJV(arrSmsJson,"idNo");//用户id
						String hsNo =GetJV(arrSmsJson,"hsNo");//华盛号
						String taskStatus =GetJV(arrSmsJson,"taskStatus");//任务状态
						String tags =GetJV(arrSmsJson,"tags");//用户标签内容
						
                        def customerpresence ="";//失效状态
						def customerpresenceid ="1";//导入结果
						def customer_guid = "";
						def objective_guid = "";
						
						//查询客户是否存在
						List custCountList2 = eliteBean.chaxun_sql("Select CUSTOMER_ID From customer Where CUSTOMER_ID = '" + hsNo + "'", "dataSource");
						if (custCountList2.size() <= 0) {
							customerpresence ="客户不存在";
							customerpresenceid ="-1";
						}else{
							// 涉及匹配顾问
							List custCountList3 = eliteBean.chaxun_sql("select HANDLEBY_ID from objective o left join customer c on o.customer_guid=c.customer_guid where c.CUSTOMER_ID = '" + hsNo + "' and o.MAP_ID='MY48ZX'", "dataSource");
							if (custCountList3.size() <= 0) {
								customerpresence ="无匹配顾问";
								customerpresenceid ="-1";
							}
							//命中查询
							if(custCountList3.size() > 0){
							List custCountList4 = eliteBean.chaxun_sql("select c.customer_guid as customer_guid,o.objective_guid as objective_guid from objective o left join customer c on o.customer_guid=c.customer_guid where c.CUSTOMER_ID = '" + hsNo + "' and o.MAP_ID='MY48ZX'", "dataSource");
								customer_guid = custCountList4.get(0).get("customer_guid");
								objective_guid = custCountList4.get(0).get("objective_guid");
							}	

							// 查询名单是否已经推送
							List custCountList = eliteBean.chaxun_sql("Select hst_no From hst_activity_batch_list Where hst_no = '" + hsNo + "' and batchname='"+tagname+"'", "dataSource");
							if (custCountList.size() > 0) {
								customerpresence ="重复";
								customerpresenceid ="-3";
							}							
						}			

							 String[] custTaskDealSQL = new String[2];
							// 插入hst_activity_batch_list 活动详情表
							custTaskDealSQL[0] = "INSERT INTO hst_activity_batch_list" +
									"  (rec_id, " +
									"  batchid, " +
									"  hst_no, " +
									"  result_code, " +
									"  result_desc, " +
									"  customer_guid, " +
									"  objective_guid, " +
									"  import_time, " +
									"  batchname) " +
									"  VALUES" +
									"  (uuid(), " +
									"  '" + batchid2 + "' ," +
									"  '" + hsNo + "' , " +
									"  '" + customerpresenceid + "' ," +
									"  '" + customerpresence + "' , " +
									"  '" + customer_guid + "' , " +
									"  '" + objective_guid + "' , " +
									"  now() , " +
									"  '" + tagname + "' )"
	
							// 插入hst_evocation_details  活动标签详情表
							custTaskDealSQL[1] = "INSERT INTO hst_evocation_details" +
									"  (primaryid, " +
									"  batchid, " +
									"  id_no, " +
									"  hs_no, " +
									"  task_status, " +
									"  tags ) " +
									"  VALUES" +
									"  (uuid(), " +
									"  '" + batchid2 + "' , " +
									"  '" + idNo + "' , " +
									"  '" + hsNo + "' , " +
									"  '" + taskStatus + "' , " +
									"  '" + tags + "')"
									
									int[] batchSQLResult = eliteBean.updateBatch(custTaskDealSQL, "dataSource");
									log.debug("SQL返回结果："+batchSQLResult.toString());
											
	                            }
	                reJson = "{\"result\":\"1\",\"lastid\":"+lastid+"}";
					log.debug("SQL返回结果："+reJson);
				}
				
				if(lastid=="0"||lastid==""){
					log.debug("bbbbbbbb");
					
					List batchidlist2 = eliteBean.chaxun_sql("select hst_no,customer_guid,objective_guid,rec_id from hst_activity_batch_list  where result_code='1' and result_desc!='已推送' and batchid='"+batchid2+"'", "dataSource");
								log.debug("batchidlist2:" + batchidlist2.size());
								if(batchidlist2.size() > 0){
								int arrInt2 = batchidlist2.size();	
									for (int t = 0; t < arrInt2; t++) {
									String customer_guid2 = batchidlist2.get(t).get("customer_guid");
									log.debug("customer_guid2:" + customer_guid2);
								    String objective_guid2 = batchidlist2.get(t).get("objective_guid");
									log.debug("objective_guid2:" + objective_guid2);
								    String hst_no2 = batchidlist2.get(t).get("hst_no");
									log.debug("objective_guid2:" + hst_no2);
									String rec_id = batchidlist2.get(t).get("rec_id");
									log.debug("rec_id:" + rec_id);
								
								    String[] custTaskDeallSQL = new String[2];
								
							        // 插入elitetask_activity表
						          	custTaskDeallSQL[0] = "INSERT INTO elitetask_activity" +
									"  (hst_no, " +
									"  batchid, " +
									"  tab_activity_id, " +
									"  customer_guid, " +
									"  objective_guid, " +
									"  Createdby, " +
									"  Createddate) " +
									"  VALUES" +
									"  ('" + hst_no2 + "' , " +
									"  '" + batchid2 + "' ," +
									"  '" + Temp_Guid + "' , " +
									"  '" + customer_guid2 + "' ," +
									"  '" + objective_guid2 + "' , " +
									"  'SELITE' , " +
									"now())"	
									
									// 修改hst_activity_batch_list状态
						          	custTaskDeallSQL[1] = "update hst_activity_batch_list set result_desc='已推送' where rec_id='"+rec_id+"'";
									
									int[] batchSQLResult2 = eliteBean.updateBatch(custTaskDeallSQL, "dataSource");
									log.debug("SQL返回结果："+batchSQLResult2.toString());
									}
								}
					
					
					//获取数据下发总量
					List file_rownumlist = eliteBean.chaxun_sql("select count(*) as file_rownum from hst_activity_batch_list where batchid= '" + batchid2 + "'", "dataSource");
                    def file_rownum = file_rownumlist.get(0).get("file_rownum");
					log.debug("file_rownum"+file_rownum);

                    //获取数据下发成功量
					List valid_numlist = eliteBean.chaxun_sql("select count(*) as valid_num from hst_activity_batch_list where batchid= '" + batchid2 + "' and result_code ='1'", "dataSource");
					def valid_num = valid_numlist.get(0).get("valid_num");
                    //获取数据下发失败量
					def invalid_num = file_rownum-valid_num;

					//def dataresult2 = eliteBean.update("INSERT INTO hst_activity_batch(rec_guid,batchid,batchname,tab_activity_id,file_name,file_rownum,valid_num,invalid_num,import_time,starttime,state,Modifiedby,Modifieddate,wholestate,batchgeneration) VALUE (uuid(), '"+batchid2+"', '接口唤回批次', '"+Temp_Guid+"', null, '"+file_rownum+"', '"+valid_num+"', '"+invalid_num+"', now(), null, '2', 'SELITE', now(), null,'待提交CRM处理')", "dataSource");

					//def dataresult3 = eliteBean.update("INSERT INTO hst_activity(tab_activity_id,tab_activity_name,tab_activity_details,tab_activity_starttime,tab_activity_endtime,tab_activity_state,Createdby,Createddate,Modifiedby,Modifieddate,tab_activity_rule,Expirationtime,isExpiration,frequency,duration) VALUES ('"+Temp_Guid+"', '"+tagname+"', '"+activity_xq+"', '"+activity_starttime+"', '"+activity_endtime+"', null, 'SELITE', now(), 'SELITE', now(), '唤回活动规则', null, null, '"+frequency+"', '"+duration+"')", "dataSource");
					
					//更新任务类型
					def dataresult4 = eliteBean.update("update hst_activity_batch set file_rownum='"+file_rownum+"',valid_num='"+valid_num+"',invalid_num='"+invalid_num+"',batchgeneration='2' where batchid= '" + batchid2 + "' and  tab_activity_id='"+Temp_Guid+"'", "dataSource");

					reJson = "{\"result\":\"1\",\"lastid\":"+lastid+",\"message\":\"标签客户获取完成\"}";
				}
            }else {
                String msg = GetJV(jsonObject, "msg");
				log.debug("ccccccccc");
                reJson = "{\"result\":\"-1\",\"message\":\"标签客户获取失败(" + msg + ")\"}";
            }
			
        } catch (Exception e) {
		    log.debug("ddddddddddd");
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
           reJson = "{\"result\":\"-1\",\"message\":\"接口异常\",\\\"lastid\\\":\"0\"}";
        }
        return reJson;
    }

    // 解析Json值
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;

		try {
			Rev_Value = String.valueOf(inJson.getBoolean(getKey));
		} catch (Exception e6) {
			try {
				Rev_Value = inJson.getString(getKey);
			} catch (Exception e5) {
				try {
					Rev_Value = String.valueOf(inJson.getInt(getKey));
				} catch (Exception e4) {
					try {
						Rev_Value = String.valueOf(inJson.getLong(getKey));
					} catch (Exception e11) {
						try {
							Rev_Value = String.valueOf(inJson.getDouble(getKey));
						} catch (Exception e1) {
							try {
								Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
							} catch (Exception e2) {
								try {
									Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
								} catch (Exception e3) {
									Rev_Value = "";
								}
							}
						}
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				Rev_Value = "";
			}
		}
		return Rev_Value;
	}


    // 非空校验isNull
    public static boolean isNull(String value) {

        boolean reFlag = true;
        if (value == "" || value.length() <= 0) {
            reFlag = true;
        } else {
            reFlag = false;
        }
        log.debug(reFlag);
        return reFlag;
    }

    // 非空校验isNullMSG
    public static String isNullMSG(String key, String value) {

        String reResult = "";
        if (value == "" || value.length() <= 0) {
            reResult = key + "必填字段;";
        }
        return reResult;
    }

}
